<?php

namespace app\xwam\model;

/**
 * Picture 模型类
 *
 * @version 1.0 2017-3-21 SoChishun(14507247@qq.com) Added.
 */
class PicturesModel extends AppbaseModel {

    protected $table = 't_picture';

    function savePicture() {
        set_time_limit(0);
        $rules = array(
            array('title', 'require', '标题无效!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
            array('category_id', 'number', '类别无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('user_name', 'require', '用户无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('site_id', 'number', 'SiteID无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        );
        if (!$validate->scene($isAdd ? true : 'edit')->check($data)) {
            return xsfn_message(false, $validate->getError());
        }
        $upload_conf = array('savePath' => 'Pictures/', 'skipEmpty' => true, 'maxSize' => 0);
        // 2016-1-13 SoChishun 修正Win服务器下rename无效的问题
        if (empty($this->auto_name) && IS_WIN) {
            $upload_conf['saveName'] = array();
        }
        $msg = \Common\Controller\UploadHandlerController::upload($upload_conf);
        if (empty($this->id) && !is_array($msg)) {
            return xsfn_message(false, $msg);
        }
        if (is_array($msg) && isset($msg['file_path'])) {
            $fileinfo = $msg['file_path'];
            $name = $fileinfo['savename'];
            $path = $fileinfo['filepath'];
            // 2015-11-17 SoChishun 修正保持原文件名,文件名是中文的时候保存出错的问题(用rename)
            if (empty($this->auto_name) && !IS_WIN) {
                $name = $fileinfo['name'];
                $path = substr($path, 0, strrpos($path, '/') + 1) . $name;
                if (!rename($fileinfo['filepath'], $path)) {
                    unlink($fileinfo['filepath']);
                    exit('重命名失败!');
                }
            }
            $data['file_name'] = $name;
            $data['file_size'] = format_bytes($fileinfo['size']);
            $data['file_type'] = $fileinfo['type'];
            $data['file_ext'] = $fileinfo['ext'];
            $data['file_path'] = $path;
        }
        /* 2017-3-21 图片改为即时上传
          if (is_array($msg) && isset($msg['picture_url'])) {
          $path = $msg['picture_url']['filepath'];
          $result = \Common\Controller\UploadHandlerController::save_thumb($path, $msg);
          if (!$result) {
          return xsfn_message(false, $msg);
          }
          $data['picture_url'] = $path;
          } */
        if (isset($data['auto_name'])) {
            unset($data['auto_name']);
        }
        $category_id = empty($data['category_id']) ? false : $data['category_id'];
        if ($isAdd) {
            unset($data['id']);
            $result = $this->isUpdate(false)->save($data);
        } else {
            $result = $this->isUpdate(true)->save($data);
        }
        if ($category_id) {
            PictureCategoryModel::updateForeignTitle(false, $category_id);
        }
        return xsfn_message($result);
    }

    function saveCategory($aid, $aCategoryId) {
        $table = $this->table;
        $sqls = array();
        $upIds = array();
        $i = 0;
        foreach ($aCategoryId as $categoryId) {
            $id = $aid[$i];
            if ($categoryId) {
                $upIds[] = $categoryId;
                $sqls[] = "update $table set category_id=$categoryId where id=$id";
            }
            $i++;
        }
        if (!$sqls) {
            return xsfn_message(false, '未选择类别!');
        }
        $mAdv = new \think\Model\AdvModel();
        $mAdv->patchQuery($sqls);
        PictureCategoryModel::updateForeignTitle(false, implode(',', $upIds));
        return xsfn_message(true);
    }

    function changeSort($id, $sort) {
        $result = $this->where(array('id' => $id))->setField(array('sort' => $sort));
        return xsfn_message($result);
    }

    function deletePicture($id) {
        $paths = $this->where(array('id' => array('in', $id)))->field('picture_url,file_path')->select();
        $result = $this->where(['id' => ['in', $id]])->delete();
        if ($result) {
            foreach ($paths as $row) {
                foreach ($row as $path) {
                    if ($path && file_exists($path)) {
                        @unlink($path);
                    }
                }
            }
        }
        return xsfn_message($result);
    }

}
